<template>
  <base-breadcrumb :title="$route.meta.title" :breadcrumb="!isAudit">
    <!-- 申报立项 -->
    <a-form-model
      ref="ruleForm"
      :model="form"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="editModel != 0 ? rules : {}"
    >
      <a-spin :spinning="loading[0] || loading[1]" style="margin-bottom: 50px">
        <a-card :bordered="false">
          <!-- 基础信息 -->
          <title-name title="基本信息"></title-name>
          <custom-form
            :formList="formList"
            :form="form"
            :orgCode.sync="form.level"
            :orgCodeName.sync="form.levelName"
            :editModel="editModel != 1 && editModel != 2 ? 'V' : ''"
            @onSelectChange="onSelectChange"
          >
            <!-- 附件上传 -->
            <template #fileInfoVOS>
              <template v-if="editModel == 1 || editModel == 2">
                <l-table businessCode="INSP1" :uploadArrys.sync="form.fileInfoVOS"></l-table>
                <div class="file_prompt">支持扩展名：.rar .zip .doc .docx .pdf .jpg...</div>
              </template>
              <file-link v-else :fileList="form.fileInfoVOS" style="margin-top: -3px"></file-link>
            </template>
          </custom-form>

          <!-- 成果上报, 活动评分实施管理表单 -->
          <!-- 标题 -->
          <title-name
            v-if="editModel != 0 && editModel != 1 && editModel != 2"
            :title="['方案上报', '过程上报', '成果上报', '活动评分'][this.editModel - 3]"
          ></title-name>
          <!-- 方案上报, 成果上报的文件上传 -->
          <a-form-model-item v-if="editModel == 3 || editModel == 5" prop="fileInfoVOS" label="标题">
            <l-table
              style="margin-top: -3px"
              businessCode="INSP1"
              :uploadArrys.sync="form[{ 3: 'reportFiles', 5: 'achievementsFiles' }[editModel]][0].fileInfoVOS"
            ></l-table>
            <div class="file_prompt">支持扩展名：.rar .zip .doc .docx .pdf .jpg...</div>
          </a-form-model-item>
          <!-- 过程上报 -->
          <ProcessEdit v-if="editModel == 4" editModel="E" :api="api" :id="id" :defaultList="form.processFiles || []" />
          <!-- 活动评分 -->
          <ActivityEvalue
            v-if="editModel == 6 && (form.typeCode || form.typeCode == 0)"
            editModel="E"
            :scoreList.sync="form.score"
            :tableType="form.typeCode"
          />
          <!-- 实施管理 -->
          <a-tabs v-if="editModel == 0" v-model="activeKey" type="card" :tabBarGutter="12">
            <a-tab-pane v-for="pane in panes" :key="pane.key" :tab="pane.title">
              <!-- 实施方案或实施成果 -->
              <template v-if="pane.key === 0 || pane.key === 2">
                <a-row type="flex" v-if="fileList.length > 0">
                  附件：<file-link :fileList="fileList"></file-link>
                </a-row>
                <empty v-else :description="`暂未上传${pane.key === 0 ? '方案' : '成果'}`" />
              </template>
              <!-- 实施过程 -->
              <template v-if="pane.key === 1">
                <ProcessEdit
                  v-if="form.processFiles && form.processFiles.length > 0"
                  editModel="V"
                  :defaultList="form.processFiles || []"
                />
                <empty v-else description="暂未添加过程" />
              </template>
              <!-- 活动评分 -->
              <template v-if="pane.key === 3">
                <ActivityEvalue
                  v-if="form.culturalScore"
                  editModel="V"
                  :total="form.culturalScore.totalScore"
                  :scoreList.sync="form.culturalScore.score"
                  :tableType="form.typeCode"
                />
                <empty v-else description="暂无活动评分" />
              </template>
            </a-tab-pane>
          </a-tabs>
        </a-card>
      </a-spin>
      <!-- 页脚操作栏 -->
      <div class="btn_box page-btn-right-top" v-if="!isConsultation && !isAudit">
        <a-button
          :loading="loading[0]"
          :disabled="loading[1]"
          v-if="(editModel == 1 && (statusCode == '0' || statusCode == '3')) || editModel == 2"
          type="primary"
          class="button_right"
          @click="handleSubmit(0)"
          >{{ statusCode == '2' || statusCode == '3' ? '保存' : '保存草稿' }}</a-button
        >
        <a-button
          :loading="loading[1]"
          :disabled="loading[0]"
          v-if="
            (editModel == 1 && (statusCode == '0' || statusCode == '3')) ||
            editModel == 2 ||
            (editModel != 0 && editModel != 4 && statusCode == '2') || editModel==4
          "
          type="primary"
          class="button_right"
          @click="handleSubmit(1)"
          >提交</a-button
        >
        <a-button type="primary" @click="handleActiveClose">关闭</a-button>
      </div>
    </a-form-model>
     <selectApprover
      :businessId="businessId"
      :processConfig="setProcessConfig"
    ></selectApprover>
  </base-breadcrumb>
</template>

<script>
import { inspCulturalConstructionDeclare } from '@/api/union/workersCongress' // api
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import Selector from '@/components/Select/Selector'
import ASelectOrgPeople from '@/components/Select/ASelectOrgPeople'
import SelectCompanyAndProject from '@/components/Select/SelectCompanyAndProject'
import ProcessEdit from './components/ProcessEdit' // 过程上报
import ActivityEvalue from './components/ActivityEvalue' // 活动评分
import { Empty } from 'ant-design-vue' // 无数据提示

export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    ProcessEdit,
    ActivityEvalue,
    Empty
  },
  props: {
    // 是否作为审批详情
    isAudit: {
      type: Boolean,
      default: false
    },
    // 是否作为意见征询
    isConsultation: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      api: inspCulturalConstructionDeclare,
      loading: { 0: false, 1: false }, // 草稿和提交按钮loding
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增;3 方案；4 过程；5 成果；6 评分
      panes: [
        {
          key: 0,
          title: '实施方案'
        },
        {
          key: 1,
          title: '实施过程'
        },
        {
          key: 2,
          title: '实施成果'
        },
        {
          key: 3,
          title: '活动评分'
        }
      ], // 实施管理的面板列表
      activeKey: 0, // 当前面板
      form: {
        phone: '',
        email: '',
        userId: void 0,
        name: void 0,
        level: '',
        levelName: '',
        reportFiles: [{}],
        achievementsFiles: [{}]
      }, // 表单
      rules: {
        typeId: [{ required: true, message: '请选择申报类型', trigger: 'change' }],
        year: [{ required: true, message: '请选择年度', trigger: 'change' }],
        unitId: [{ required: true, message: '请选择单位', trigger: 'change' }],
        userId: [{ required: true, message: '请选择联系人', trigger: 'change' }],
        remarks: [{ required: true, whitespace: true, message: '请输入主要内容', trigger: 'change' }],
        amountOfMoney: [{ required: true, message: '请输入合同金额（万元）', trigger: 'change' }],
        address: [{ required: true, whitespace: true, message: '请输入项目所在地', trigger: 'change' }],
        fileInfoVOS: [{ type: 'array', required: true, message: '请上传附件', trigger: 'blur' }]
      }, // 校验规则
      init: false, // 初始化控件
      statusCode: '', // 审批状态
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  watch: {
    // 监听附件实现附件校验
    'form.fileInfoVOS'() {
      if (this.editModel != 0 && this.init) {
        this.$nextTick(() => {
          this.$refs.ruleForm?.validateField('fileInfoVOS')
        })
      }
    }
  },
 async mounted() {
    this.$route.meta.title = ['文化建设活动查看', '文化建设活动编辑', '文化建设活动新增'][this.editModel]
    // 不为添加时请求详情
    if (this.editModel != 2) {
      this.getInfo()
    } else {
      this.$nextTick(() => {
        // 默认映射联系人为登陆人
        this.form.name = this.$userInfo().name
        this.form.userId = this.$userInfo().id
        this.form.email = this.$userInfo().employee.email
        this.form.phone = this.$userInfo().employee.phone
        // 映射层级
        this.form.level = this.$currentPost().code
        this.form.levelName = { CO: '公司', BC: '分公司', PD: '项目' }[this.$currentPost().code]
        this.init = true
      })
    }
     //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('cultural_construction_declare')
  },
  computed: {
    // 实施管理文件
    fileList() {
      return this.form[{ 0: 'reportFiles', 2: 'achievementsFiles' }[this.activeKey]]?.[0]?.fileInfoVOS ?? []
    },
    // 表单列表
    formList() {
      return [
        {
          keyName: 'typeId',
          viewName: 'typeName',
          label: '申报类型',
          placeholder: '请选择申报类型',
          type: Selector,
          attrs: {
            selectType: '7',
            urlType: 'union'
          }
        },
        {
          keyName: 'year',
          type: 'a-date-picker',
          label: '年度',
          attrs: {
            mode: 'year',
            format: 'YYYY',
            valueFormat: 'YYYY'
          }
        },
        {
          keyName: 'levelName',
          label: '层级',
          placeholder: '请选择层级',
          type: 'BaseInput',
          disabled: true
        },
        {
          keyName: 'unitId',
          viewName: 'unitName',
          placeholder: '请选择单位',
          type: SelectCompanyAndProject,
          label: '单位'
        },
        {
          keyName: 'amountOfMoney',
          viewName: 'money',
          precision: 2,
          type: 'BaseInputNumber',
          label: '合同金额（万元）'
        },
        {
          keyName: 'address',
          type: 'BaseInput',
          label: '项目所在地'
        },
        {
          keyName: 'userId',
          viewName: 'name',
          type: ASelectOrgPeople,
          label: '联系人',
          attrs: {
            selectPeopleName: this.form.name,
          }
        },
        {
          keyName: 'phone',
          type: 'BaseInput',
          disabled: true,
          label: '联系电话'
        },
        {
          keyName: 'email',
          type: 'BaseInput',
          disabled: true,
          label: '邮箱'
        },
        {
          keyName: 'remarks',
          type: 'BaseTextarea',
          label: '备注',
          span: 24
        },
        {
          slot: true,
          keyName: 'fileInfoVOS',
          label: '附件',
          span: 24
        }
      ]
    }
  },
  methods: {
    /**
     * 获取详情
     */
    getInfo() {
      this.loading[0] = true
      inspCulturalConstructionDeclare
        .getDetail({ id: this.id })
        .then((res) => {
          this.loading[0] = false
          this.statusCode = res.data?.status
          // 默认上报方案文件
          if (!res.data.reportFiles) {
            res.data.reportFiles = [{}]
          }
          // 默认上报方案文件
          if (!res.data.achievementsFiles) {
            res.data.achievementsFiles = [{}]
          }
          // 转义评分格式
          if (res.data.culturalScore?.score) {
            res.data.culturalScore.score = res.data.culturalScore.score.split(',')
          }
          this.form = res.data
          this.$nextTick(() => {
            this.init = true
          })
        })
        .catch(() => {
          this.loading[0] = false
        })
    },
    /**
     * 选择人员回调
     */
    onSelectChange() {
      if (arguments[0] === 'userId') {
        // 映射邮箱
        this.form.email = arguments[1].email
        // 映射姓名
        this.form.name = arguments[1].name
        // 映射手机
        this.form.phone = arguments[1].phone
      }
    },
    /**
     * 提交表单
     */
    handleSubmit(statusCode) {
      let that = this
      that.setProcessConfig = null
      // 校验表单
      that.$refs.ruleForm.validate((e) => {
        // if (e) {
        // 表单校验通过或者保存草稿
        if (e || statusCode === 0) {
          let url = inspCulturalConstructionDeclare // api地址
          let api = ['update', 'create'][that.editModel - 1] // api名称
          let form = that.$clone(that.form)
          // 清除校验
          statusCode === 0 && that.$refs.ruleForm.clearValidate()
          /**
           * 当是申报操作时
           */
          if (that.editModel < 3) {
            // 格式化文件列表
            if (form.fileInfoVOS?.length > 0) {
              form.fileId = form.fileInfoVOS.map((item) => item.commonId).join()
            }
            if (typeof form.year !== 'string') {
              form.year = that.$dateFormat(form.year, 'Y')
            }
          } else if (that.editModel == 6) {
            /**
             * 当是活动评分操作时
             */
            api = 'create'
            url = require('@/api/union/workersCongress').inspCulturalScore
            form = {
              score: form.score,
              declareId: form.id
            }
            if (
              !form.score ||
              form.score.some(
                (item, index) =>
                  (index != form.score.length - 1 && !item) || (index == form.score.length - 1 && !item && item != 0)
              )
            ) {
              that.$message.warning('请完成评分后提交')
              return
            } else {
              form.score = form.score.join()
            }
          } else {
            /**
             * 当是上报操作时
             */
            let fileName = { 3: 'reportFiles', 5: 'achievementsFiles' }[that.editModel] // 文件参数名：3 方案上报；5 成果上报
            url =
              require('@/api/union/workersCongress')[
                { 3: 'inspCulturalReportFile', 4:'inspCulturalProcessFile',5: 'inspCulturalAchievementsFile' }[that.editModel]
              ] // 请求地址：3 方案上报；5 成果上报
            api = form[fileName]?.[0].declareId ? 'update' : 'create' // 若declareId存在则进行更新操作，否则进行添加操作
            form = {
              id: form[fileName]?.[0].id,
              declareId: form.reportFiles?.[0].declareId || form.id
            }
            // 格式化文件列表
            if (that.form[fileName]?.[0]?.fileInfoVOS?.length > 0) {
              form.fileId = that.form[fileName]?.[0]?.fileInfoVOS.map((item) => item.commonId).join()
            }
          }
          // 动态添加审批状态参数
          form.status =
            (that.statusCode == '3' && statusCode == 0) || (that.statusCode == '2' && statusCode == 1)
              ? that.statusCode
              : statusCode
          // 转译年度参数
          that.loading[statusCode] = true
          // 提交请求
          this.submitApprovalConfirm(statusCode*1 ===1  ? this.processConfig : 6, async (flag)=>{
          if(!flag) {
            this.loading[statusCode] = false
            return
          }
          console.log( url[api],' url[api]')
          url[api](form)
            .then((res) => {
              that.loading[statusCode] = false
              that.$message.success(['保存', '提交'][statusCode] + '成功！')
              if(statusCode*1 ===1 && this.editModel*1 ===2 &&  this.form.level != 'CO'){
                //提交时，返回id
                 that.businessId = res.data || that.$route.query.id
                 that.setProcessConfig = that.processConfig
              }else{
                 that.$multiTab.close()
              }
            })
            .catch(() => {
              that.loading[statusCode] = false
            })
          })
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ .ant-form-item {
  .ant-form-item-label {
    height: 28px;
    width: 150px;
    line-height: 22px;
    padding: 6px 4px 0 0;
    text-align: right;
    white-space: pre-wrap;
    overflow: visible;
  }
  .ant-form-item-control-wrapper {
    width: calc(100% - 150px);
  }
}
.file_prompt {
  color: #999;
}
</style>